package top.lingkang.websocketlivechrome.ws;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author lingkang
 * Created by 2021/12/21
 */
@Component //注册成组件，用于使用 HttpServletRequest ，从而更容易验证
public class AuthHandshakeInterceptor implements HandshakeInterceptor {
    @Autowired
    private HttpServletRequest httpServletRequest;

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        //用于鉴权，例如 /ws?token=zhangsan
        String token = httpServletRequest.getParameter("token");
        System.out.println(token);
        if (!"123".equals(token)) {
            HttpServletResponse servletResponse = (HttpServletResponse) response;
            servletResponse.getWriter().println("<script>alert('未授权的websocket连接！')</script>");
            return false;
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
